package cn.ctvonline.android.kaopu.activity;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.StateListDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.ctvonline.android.kaopu.R;
import cn.ctvonline.android.kaopu.base.BaseAppCompatActivity;
import cn.ctvonline.android.kaopu.base.IncomingHandler;
import cn.ctvonline.android.kaopu.base.MessageHandleListener;

/**
 * 相册查看
 */
public class PhotoAlbumActivity extends BaseAppCompatActivity {
    private RecyclerView mPhotoAlbumRv;
    private AlbumAdapter mAlbumAdapter;
    private final String IMAGE_TYPE = "image/*";
    private final int IMAGE_PICK_CODE = 0x0a;
    private final int TAKE_CAMERA_CODE = 0x09;
    private ArrayList<ImageInfo> imageInfos;
    private List<String> folders = new ArrayList<>();
    private IncomingHandler<PhotoAlbumActivity> handler;
    static final int QUERY_IMAGES_OK = 0x01;
    private String lastPhotoPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_album_acrivity);
        findViews();
        initHandler();
        loadSystemPhotos();
    }

    private void initHandler() {
        handler = getHandler();
        handler.setOnMessageHandleListener(new MessageHandleListener() {
            @Override
            public void onHandlerMessage(Message msg) {
                switch (msg.what) {
                    case QUERY_IMAGES_OK: {
                        Map<String, List<ImageInfo>> result = ((Map<String, List<ImageInfo>>) msg.obj);
                        for (List<ImageInfo> list : result.values()) {
                            imageInfos.addAll(list);
                        }
                        mAlbumAdapter.notifyDataSetChanged();
                    }
                    break;
                }
            }
        });
    }

    private MenuItem searchItem, settingItem, shareItem;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_search, menu);
        searchItem = menu.findItem(R.id.action_search);
        settingItem = menu.findItem(R.id.action_settings);
        shareItem = menu.findItem(R.id.action_share);
        return true;
    }

    private void loadSystemPhotos() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, List<ImageInfo>> map = queryImages();
                Message msg = Message.obtain();
                msg.what = QUERY_IMAGES_OK;
                msg.obj = map;
                handler.sendMessage(msg);
            }
        }).start();
    }

    protected void findViews() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.photo_album_tb);
        setSupportActionBar(toolbar);
        mPhotoAlbumRv = (RecyclerView) findViewById(R.id.photo_rv);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        mPhotoAlbumRv.setLayoutManager(gridLayoutManager);
        mAlbumAdapter = new AlbumAdapter(this);
        imageInfos = new ArrayList<ImageInfo>();
        imageInfos.add(null);
        mPhotoAlbumRv.addItemDecoration(new PhotoItemDecoration());
        mPhotoAlbumRv.setAdapter(mAlbumAdapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (TAKE_CAMERA_CODE == requestCode) {
                File file = new File(lastPhotoPath);
                ImageInfo imageInfo = new ImageInfo(lastPhotoPath, file.getName(), "");
                imageInfos.add(1, imageInfo);
                mAlbumAdapter.notifyDataSetChanged();
            } else if (data.getType() == IMAGE_TYPE && requestCode == IMAGE_PICK_CODE) {
                try {
                    Uri uri = data.getData();
                    ContentResolver cResolver = getContentResolver();
                    MediaStore.Images.Media.getBitmap(cResolver, uri);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private Map<String, List<ImageInfo>> queryImages() {
        Map<String, List<ImageInfo>> result = new HashMap<>();
        ContentResolver cResolver = getContentResolver();
        String[] columns = {MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.ORIENTATION};
        Cursor cursor = cResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                columns, "", null,
                MediaStore.MediaColumns.DATE_ADDED + " DESC");
        Log.e("TAG", cursor.getCount() + "");
        if (cursor != null && cursor.moveToFirst()) {
            int _date = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
            int _display_name = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME);
            int _orientation = cursor.getColumnIndex(MediaStore.Images.Media.ORIENTATION);
            while (cursor.moveToNext()) {
                String path = cursor.getString(_date);
                String displayName = cursor.getString(_display_name);
                String orientation = cursor.getString(_orientation);
                String logs = "path=" + path + ",displayName=" + displayName + ",orientation=" + orientation;
                Log.i(TAG, logs);
                File imageFile = new File(path);
                String folder = imageFile.getParentFile().getName();
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(imageFile);
                    if (imageFile != null && imageFile.exists() && fis.available() > 0) {
                        folders.add(folder);
                        ImageInfo imageInfo = new ImageInfo("file://" + imageFile.getPath(), displayName, orientation);
                        List<ImageInfo> list = null;
                        if (result.containsKey(folder)) {
                            list = result.get(folder);
                        } else {
                            list = new ArrayList<>();
                        }
                        list.add(imageInfo);
                        result.put(folder, list);
                    }
                } catch (Exception e) {
                    try {
                        if (fis != null)
                            fis.close();
                        fis = null;
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
            }
            cursor.close();
        }
        return result;
    }

    class ImageInfo {
        String imagePath;
        String displayName;
        String orientation;

        public ImageInfo(String imagePath, String displayName, String orientation) {
            this.imagePath = imagePath;
            this.displayName = displayName;
            this.orientation = orientation;
        }
    }

    @Override
    protected String generatePageName() {
        return "PhotoAlbumActivity";
    }

    class AlbumAdapter extends RecyclerView.Adapter {
        LayoutInflater inflater;

        public AlbumAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        @Override
        public int getItemCount() {
            return imageInfos.size();
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            Log.i(TAG, "this is position = " + position);
            //设置值
            final ImageInfo imageInfo = imageInfos.get(position);
            final ViewHolder vh = (ViewHolder) holder;
            if (position == 0) {
                vh.photoIv.setImageBitmap(null);
                vh.photoTv.setVisibility(View.VISIBLE);
                vh.photoCb.setVisibility(View.GONE);
                StateListDrawable stateListDrawable = new StateListDrawable();
                stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, getResources().getDrawable(R.mipmap.icon_camera_normal));
                stateListDrawable.addState(new int[]{}, getResources().getDrawable(R.mipmap.icon_camera_normal));
                vh.photoIv.setBackgroundDrawable(stateListDrawable);
                vh.view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        //保存
                        File saveDir = new File(Environment.getExternalStorageDirectory().getPath() + "/" + getPackageName() + "/photo/");
                        if (saveDir != null && !saveDir.exists()) {
                            saveDir.mkdirs();
                        }
                        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                        File mediaFile = new File(saveDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
                        lastPhotoPath = "file://" + mediaFile.getAbsolutePath();
                        Uri uri = Uri.fromFile(mediaFile);
                        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                        startActivityForResult(cameraIntent, TAKE_CAMERA_CODE);
                    }
                });
            } else {
                vh.photoTv.setVisibility(View.GONE);
                vh.photoCb.setVisibility(View.VISIBLE);
                vh.view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getApplicationContext(), ImageShowActivity.class);
                        intent.putExtra("imageUri", imageInfo.imagePath);
                        startActivity(intent);
                    }
                });
                vh.photoCb.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (vh.photoCb.isChecked()) {
                            vh.view.setAlpha(0.6f);
                        } else {
                            vh.view.setAlpha(1.0f);
                        }
                    }
                });
//                BitmapFactory.Options options = new BitmapFactory.Options();
//                options.outWidth = 100;
//                options.outHeight = 100;
//                options.inJustDecodeBounds = true;
//                options.inPreferredConfig = Bitmap.Config.ARGB_4444;
//                Bitmap loadedImage = BitmapFactory.decodeFile(imageInfo.imagePath, options);
//                if (loadedImage != null && imageInfo.orientation != null && !"".equals(imageInfo.orientation) && "90".equals(imageInfo.orientation)) {
//                    Matrix matrix = new Matrix();
//                    matrix.setRotate(Integer.parseInt(imageInfo.orientation));
//                    Bitmap bitmap = Bitmap.createBitmap(loadedImage, 0, 0, loadedImage.getWidth(), loadedImage.getHeight(), matrix, true);
//                    vh.photoIv.setImageBitmap(bitmap);
//                }
                DisplayImageOptions.Builder optBuilder = new DisplayImageOptions.Builder();
                optBuilder.imageScaleType(ImageScaleType.IN_SAMPLE_INT);
                optBuilder.showImageOnLoading(R.mipmap.logo);
                optBuilder.bitmapConfig(Bitmap.Config.RGB_565);
                optBuilder.delayBeforeLoading(0);
                DisplayImageOptions options = optBuilder.build();
                ImageLoader.getInstance().displayImage(imageInfo.imagePath, vh.photoIv, options, new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                        if (loadedImage != null) {
                            Bitmap bitmap = loadedImage;
                            if (imageInfo.orientation != null && !"".equals(imageInfo.orientation) && "90".equals(imageInfo.orientation)) {
                                Matrix matrix = new Matrix();
                                matrix.setRotate(Integer.parseInt(imageInfo.orientation));
                                bitmap = Bitmap.createBitmap(loadedImage, 0, 0, loadedImage.getWidth(), loadedImage.getHeight(), matrix, true);
                            }
                            vh.photoIv.setImageBitmap(bitmap);
                        }
                    }
                });
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = inflater.inflate(R.layout.photo_album_item, parent, false);
            ViewHolder viewHolder = new ViewHolder(view);
            return viewHolder;
        }
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        ImageView photoIv;
        TextView photoTv;
        CheckBox photoCb;
        View view;

        ViewHolder(View view) {
            super(view);
            this.view = view;
            photoIv = (ImageView) view.findViewById(R.id.album_photo_item_iv);
            photoTv = (TextView) view.findViewById(R.id.album_photo_item_tv);
            photoCb = (CheckBox) view.findViewById(R.id.album_photo_item_cb);
        }
    }

    class PhotoItemDecoration extends RecyclerView.ItemDecoration {
        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            //先初始化一个Paint来简单指定一下Canvas的颜色，就黑的吧！
            Paint paint = new Paint();
            paint.setColor(parent.getContext().getResources().getColor(android.R.color.black));
            paint.setAntiAlias(true);
            paint.setStrokeWidth(4);
            //获得RecyclerView中总条目数量
            int childCount = parent.getChildCount();
            //遍历一下
            for (int i = 0; i < childCount; i++) {
//                if (i == 0) {
//                    //如果是第一个条目，那么我们就不画边框了
//                    continue;
//                }
                //获得子View，也就是一个条目的View，准备给他画上边框
                View childView = parent.getChildAt(i);

                //先获得子View的长宽，以及在屏幕上的位置，方便我们得到边框的具体坐标
                float x = childView.getX();
                float y = childView.getY();
                int width = childView.getWidth();
                int height = childView.getHeight();

                //根据这些点画条目的四周的线
                c.drawLine(x, y, x + width, y, paint);
                c.drawLine(x, y, x, y + height, paint);
                c.drawLine(x + width, y, x + width, y + height, paint);
                c.drawLine(x, y + height, x + width, y + height, paint);

                //当然了，这里大家肯定是要根据自己不同的设计稿进行画线，或者画一些其他的东西，都可以在这里搞，非常方便
            }
            super.onDraw(c, parent, state);
        }
    }
}
